/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/flatten-binary-tree-to-linked-list
   @Language: C++
   @Datetime: 16-02-09 04:47
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

// Method 1
class Solution {
public:
	/**
	 * @param root: a TreeNode, the root of the binary tree
	 * @return: nothing
	 */
	void flatten(TreeNode *root) {
		// write your code here
		if (root==NULL)
			return ;
		TreeNode *t=root->right;
		root->right = root->left;
		flatten(root->left);     
		root->left = NULL;
		for(root;root->right;root=root->right);       
		root->right = t;
		flatten(t);
	}
};



// Method 2
class Solution {
	void postorder(TreeNode *root, TreeNode **next){
		if(root==NULL) return;
		postorder(root->right,next);
		postorder(root->left,next);
		root->right=*next;
		root->left=NULL;
		*next=root;
	}
public:
	/**
	 * @param root: a TreeNode, the root of the binary tree
	 * @return: nothing
	 */
	void flatten(TreeNode * root) {
		// write your code here
		TreeNode *next=NULL;
		postorder(root,&next);
	}
};
